<template>
  <page-header-wrapper>
    <page-tab-list></page-tab-list>

    <a-card :bordered="false">
      <a-form-model 
        :labelCol="{ span: 4 }"
        :wrapperCol="{ span: 18 }">
        <a-form-model-item label="小程序" prop="id">
          <a-select 
            placeholder="请选择小程序"  
            v-model="id"
            @change="getData">
            <a-select-option :value="item.id" v-for="item of idList" :key="item.id">
              {{ item.app_name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>

      <template v-if="id">
        <a-alert v-if="check.code" type="error" :message="check.msg" banner />
        <a-divider orientation="left">
          配送配置
        </a-divider>
        <a-form-model
          ref="coordinateForm"
          :model="config"
          :rules="infoRules"
          :labelCol="{ span: 4 }"
          :wrapperCol="{ span: 18 }"
        >
          <a-form-model-item label="配送方式" prop="logistics_codes">
            <a-radio-group v-model="config.logistics_codes">
              <a-radio 
                :value="item.logistics_code" 
                v-for="item of deliveryList" 
                :key="item.logistics_code"> {{item.logistics_name}} </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-alert v-if="getStatus" type="error" :message="getStatus" banner />

          <a-form-model-item label="企业全称">
            <a-input disabled v-model="config.enterprise_name" />
          </a-form-model-item>
          
          <a-form-model-item label="统一社会信用代码">
            <a-input disabled v-model="config.credit_code" />
          </a-form-model-item>

          <a-form-model-item label="企业所在地">
            <a-cascader 
              :value="[enterprise_province,enterprise_city,enterprise_district]"
              disabled
              :options="areaList"
              :fieldNames="{
                label: 'name', value: 'adcode', children: 'children'
              }"
              />
          </a-form-model-item>

          <a-form-model-item label="企业地址">
            <a-input disabled v-model="config.enterprise_address" />
          </a-form-model-item>

          <a-form-model-item label="经营范围">
            <a-input disabled v-model="config.business_scope" />
          </a-form-model-item>

          <a-form-model-item label="企业营业执照图片正反面">
            <cyyUploadImg
              :disabled="true"
              @uploadSuccess="(e)=>config.business_license = e.data"
              @deleteImg="config.business_license = ''"
              :imgSrc="config.business_license"
            >
            </cyyUploadImg>
          </a-form-model-item>

          <a-form-model-item label="联系人手机号">
            <a-input disabled v-model="config.phone" />
          </a-form-model-item>

          <a-form-model-item label="联系人邮箱">
            <a-input disabled v-model="config.email" />
          </a-form-model-item>

          <a-form-model-item label="账户余额">
            <a-input disabled v-model="config.balance" />
          </a-form-model-item>

          <a-form-model-item :wrapper-col="{ span: 12, offset: 6 }">
            <a-button :loading="btnLoading" type="primary" @click="submitForm">
              保存
            </a-button>
          </a-form-model-item>
        </a-form-model>

          <a-divider orientation="left">
            门店设置
          </a-divider>
          <a-form-model
            ref="storeForm"
            :rules="storeRules"
            :model="storeData"
            :labelCol="{ span: 4 }"
            :wrapperCol="{ span: 18 }"
          >
            <a-form-model-item label="门店名称" prop="shop_name">
              <a-input v-model="storeData.shop_name" />
            </a-form-model-item>

            <a-form-model-item label="店铺类目" prop="shop_category">
              <a-input v-model="storeData.shop_category" />
              <div>
                <a 
                  href="https://mif-pub.alipayobjects.com/ShopCategory.xlsx"
                  target="_blank">取值参见文件https://mif-pub.alipayobjects.com/ShopCategory.xlsx 中的三级门店类目</a>
              </div>
            </a-form-model-item>

            <a-form-model-item label="所在地" required>
              <a-cascader 
                :value="[
                  storeData.enterprise_province,
                  storeData.enterprise_city,
                  storeData.enterprise_district
                ]"
                :options="areaList"
                :fieldNames="{
                  label: 'name', value: 'adcode', children: 'children'
                }"
                @change="changeArea"
                />
            </a-form-model-item>

            <a-form-model-item 
              prop="detail_address"
              label="地址" help="商户详细经营地址或人员所在地点">
              <a-input v-model="storeData.detail_address" />
            </a-form-model-item>

            <a-form-model-item label="坐标" prop="location">
              <a-input-search
                @search="select_map_visiable = !select_map_visiable"
                placeholder="选择坐标"
                v-model="location"
                :readOnly="true"
              >
                <a-button slot="enterButton">搜索地图</a-button>
              </a-input-search>
            </a-form-model-item>

            <a-form-model-item prop="contact_name" label="联系人姓名">
              <a-input v-model="storeData.contact_name" />
            </a-form-model-item>

            <a-form-model-item label="联系人电话" prop="phone">
              <a-input v-model="storeData.phone" />
            </a-form-model-item>

            <a-form-model-item :wrapper-col="{ span: 12, offset: 6 }">
              <a-button :loading="btnLoading" type="primary" @click="storeSubmitForm">
                保存
              </a-button>
            </a-form-model-item>
          </a-form-model>
        <!-- <template v-if="!check.code">
        </template> -->
      </template>
    </a-card>

    <SelectMap
      v-if="select_map_visiable"
      :value.sync="select_map_visiable"
      :oldmarker="location"
      :inputDefault="location"
      @onOk="
        e => {
          location = e
        }
      "
    ></SelectMap>
  </page-header-wrapper>
</template>

<script>
import storage from 'store'
import {
  companyList,
  createAccount,
  queryAccount,
  createMd,
  queryMd,
  deliveryConf
} from "@/api/alipayDelivery"
import { alipayList } from '@/api/setting/applet'
import { areaList } from '@/api/marketing/alipayPromotion'
import {  cyyUploadImg } from '@/components/CyyUi/index'
import SelectMap from '@/components/SelectMap/SelectMap'


export default {
  name: 'alipayDelivery',
  components: {
    SelectMap,
    cyyUploadImg
  },

  computed:{
    getStatus(){
      let {logistics_account_status,config} = this;
      if(logistics_account_status.length){
        let  item = logistics_account_status.find(el=>el.logistics_code === config.logistics_codes);
        return item && item.status !== 'VALID'  ? item.audit_desc : ''
      }
      return ''
    }
  },
  data() {
    return {
      // type: 1,
      store_id: 0,
      loading: false,
      btnLoading: false,
      id:'',
      config: {
        logistics_codes:"",
        enterprise_type:"", // 企业类型
        enterprise_name:"", // 企业全称
        credit_code:'', // 统一社会信用代码
        enterprise_province:"", // 企业所在地，省编码
        enterprise_city:'', // 企业所在地，市编码
        enterprise_district:"", // 企业所在地，区编码
        enterprise_address:"", // 企业地址
        business_scope:"", // 经营范围
        business_license:"", // 企业营业执照图片正反面
        phone:"", // 联系人手机号
        email:"", // 联系人邮箱
        balance:"", // 账户余额
        logistics_account_status:[]
      },

      infoRules:{
        logistics_codes: [
          { required: true, message: '请选择配送方式', trigger: 'change' },
        ],
      },

      idList:[],
      deliveryList:'',
      areaList:[],

      storeData:{
        shop_name:'', // 门店名称
        shop_category:"", // 店铺类目
        enterprise_province:"",
        enterprise_city:"",
        enterprise_district:"",
        detail_address:'', // 地址
        contact_name:"", // 联系人姓名
        phone:"", // 联系人电话/手机号
        longitude:"",
        latitude:"",
      },

      storeRules:{
        shop_name: [
          { required: true, message: '请输入门店名称', trigger: 'blur' },
        ],
        shop_category: [
          { required: true, message: '请输入店铺类目', trigger: 'blur' },
        ],
        // enterprise_province:[
        //   {
        //     required: true,message: '请输入店铺类目', trigger: 'change'
        //   }
        // ],
        detail_address: [
          { required: true, message: '请输入地址', trigger: 'blur' },
        ],
        contact_name: [
          { required: true, message: '请输入联系人姓名', trigger: 'blur' },
        ],
        phone: [
          { required: true, message: '请输入联系人电话', trigger: 'blur' },
        ],
        location: [{ validator: (rule, value, callback) => {
          if (this.location == '') {
            callback(new Error('请选择坐标'))
          } else {
            callback()
          }
        }, trigger: 'change' }],
      },
      // 选中的坐标
      location: '',
      // 是否显示选择地图的组件
      select_map_visiable: false,
      check:{
        code:1,
        msg:""
      },
      logistics_account_status:null
    }
  },

  async created() {
    const hide = this.$message.loading('请稍等', 0),
      res = await alipayList();

    if (!res.code && res.data.length) {
      this.idList = res.data
    }else{
     this.$message.error(res.msg)
    }

    hide()
    areaList().then(res=>{
      if(!res.code){
        this.areaList = res.data.area_code || [];
      }
    })
  },

  methods: {
    changeArea(e){
      this.storeData.enterprise_province = e[0];
      this.storeData.enterprise_city = e[1];
      this.storeData.enterprise_district = e[2];
    },

    getData() {
      let {id} = this,
      store_id = storage.get('storeId');
      this.store_id = store_id;
      this.loading = true;

      Promise.all([companyList({
        id,
        store_id
      })
      ,
      deliveryConf({
        id,
        store_id
      })
      // queryAccount({
      //   id,
      //   store_id
      // }),queryMd({
      //   id,
      //   store_id
      // })
    
    ]).then(res=>{
        this.loading = false
        res.forEach((el,i)=>{
          if(el.code){
            this.$message.error(el.msg)
          }

          switch(i){
            case 0:
              if(el.data && el.data.logistics_companies && el.data.logistics_companies.length){
                this.deliveryList = el.data.logistics_companies;
                // this.config.logistics_codes = el.data.logistics_companies[0].logistics_code
              }
              break

            case 1:

              let {check,md,company,account} = el.data;

              if(account.data && account.data.logistics_account_status){
                this.logistics_account_status = account.data.logistics_account_status
              }
   
              if(check.code){
                this.check = {
                  code:1,
                  msg : check.msg
                }
              }
              
              if(!account.code){
                let {
                    enterprise_type,
                    enterprise_name,
                    credit_code,
                    enterprise_province,
                    enterprise_city,
                    enterprise_district,
                    enterprise_address,
                    business_scope,
                    business_license,
                    phone,
                    email,
                    balance,
                  } = account.data;
                  this.config = {
                    enterprise_type,
                    enterprise_name,
                    credit_code,
                    enterprise_province,
                    enterprise_city,
                    enterprise_district,
                    enterprise_address,
                    business_scope,
                    business_license,
                    phone,
                    email,
                    balance
                  }
             }

              if(!md.code){
                let {
                  shop_name,
                  shop_category,
                  enterprise_province,
                  enterprise_city,
                  enterprise_district,
                  detail_address,
                  contact_name,
                  phone,
                  longitude,
                  latitude,
                } = md.data;

                this.storeData = {
                  shop_name,
                  shop_category,
                  enterprise_province,
                  enterprise_city,
                  enterprise_district,
                  detail_address,
                  contact_name,
                  phone,
                  longitude,
                  latitude,
                }

                this.location = `${latitude},${longitude}`;
              }

              this.config.logistics_codes = company
              break
            // case 1:
            //   if(el.data){
            //     let {
            //       enterprise_type,
            //       enterprise_name,
            //       credit_code,
            //       enterprise_province,
            //       enterprise_city,
            //       enterprise_district,
            //       enterprise_address,
            //       business_scope,
            //       business_license,
            //       phone,
            //       email,
            //       balance
            //     } = el.data;

            //     this.config = {
            //       enterprise_type,
            //       enterprise_name,
            //       credit_code,
            //       enterprise_province,
            //       enterprise_city,
            //       enterprise_district,
            //       enterprise_address,
            //       business_scope,
            //       business_license,
            //       phone,
            //       email,
            //       balance
            //     }

                
            //   }
            //   break

            // case 2:
            //     if(el.data){
            //       let {
            //         shop_name,
            //         shop_category,
            //         enterprise_province,
            //         enterprise_city,
            //         enterprise_district,
            //         detail_address,
            //         contact_name,
            //         phone,
            //         longitude,
            //         latitude,
            //       } = el.data;

            //       this.storeData = {
            //         shop_name,
            //         shop_category,
            //         enterprise_province,
            //         enterprise_city,
            //         enterprise_district,
            //         detail_address,
            //         contact_name,
            //         phone,
            //         longitude,
            //         latitude,
            //       }

            //       this.location = `${latitude},${longitude}`;
            //     }
            //   break
          }

          // this.config.logistics_codes = res[2].conf.company
        })
      }).catch(()=>{
        this.loading = false
      })
    },

    submitForm() {
      let {store_id,id} = this,
      config = JSON.parse(JSON.stringify(this.config));

      if(!config.logistics_codes) return this.$message.error('请选择配送方式~');
      config.logistics_codes = [config.logistics_codes]

      // this.$refs.coordinateForm.validate(valid => {
        // if (valid) {
          this.btnLoading = true
          createAccount({
            ...config,
            store_id,
            id
          })
            .then(res => {
              if (res.code == 0) {
                let {status,audit_desc} = res.data.logistics_account_status[0];

                if(status !== 'AUDITING'){
                  this.$message.error(`${status},${audit_desc}`)
                  return;
                }

                this.$message.success('保存成功！')
              } else {
                this.$message.warning(res.msg ? res.msg : '保存失败！')
              }
            })
            .catch(error => {
              console.log(error)
            })
            .then(() => {
              this.btnLoading = false
            })
        // }
      // })
    },

    storeSubmitForm(){
      this.$refs.storeForm.validate(valid => {
        if (valid) {
          let {storeData,id,location,store_id} = this,
            newData = JSON.parse(JSON.stringify(storeData));
          newData.latitude = location.split(',')[0]
          newData.longitude = location.split(',')[1]
          this.loading = true;

          createMd({
            store_id,
            ...storeData,
            id
          }).then(res=>{
            this.loading = false;
            if(!res.code){
              this.$message.success('设置成功~');
              return;
            }
            
            this.$message.error(res.msg)
          }).catch(()=>{
            this.loading = false;
          })
        }
      })
    }
  }
}
</script>

<style scoped></style>
